package com.yingpai.fitness.dvp_2_0.common.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.FinalOkgo;
import com.yingpai.fitness.dvp_2_0.common.util.Utils;

import butterknife.OnClick;

/**
 * Created by ASUS on 2018/2/6.
 */

public abstract class CommonFragment extends Fragment {
    protected Activity context;
    protected Dialog loadingDialog;
    protected String fragmentTitle;             //fragment标题
    private boolean isVisible;                  //是否可见状态
    private boolean isPrepared;                 //标志位，View已经初始化完成。
    private boolean isFirstLoad = true;         //是否第一次加载
    protected LayoutInflater inflater;
    protected FinalOkgo finalOkGo;
    protected RxPermissions rxPermissions;

    public CommonFragment() {
        // Required empty public constructor
    }

    /**
     * 如果 Fragment 持有宿主 Activity 的引用，会导致宿主 Activity 无法回收，
     * 造成内存泄漏。所以，如果可以的话，尽量不要在 Fragment 中持有宿主 Activity 的引用。
     为了解决 Context 上下文引用的问题，Fragment 提供了一个 onAttach(context) 方法，
     在此方法中我们可以获取到 Context 对象
     * @param context
     */
    @Override
    public void onAttach(Context context)
    {
        super.onAttach(context);
        this.context = (Activity) context;
        if (finalOkGo == null) {
            finalOkGo = new FinalOkgo(context);
        }
        if(rxPermissions==null){
            rxPermissions = new RxPermissions(this.context);
        }
    }

    public void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent(context, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        ActivityCompat.startActivity(context,intent, ActivityOptionsCompat.makeSceneTransitionAnimation((Activity)context).toBundle());
    }

    public void startActivity(Class<?> cls) {
        Intent intent = new Intent(context, cls);
        ActivityCompat.startActivity(context,intent, ActivityOptionsCompat.makeSceneTransitionAnimation((Activity)context).toBundle());
    }

    public void startFinishActivity(Class<?> cls) {
        Intent intent = new Intent(context, cls);
        startActivity(intent);
        context.finish();
    }

    public void startFinishActivity(Class<?> cls, @Nullable Bundle bundle) {
        Intent intent = new Intent(context, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        context.finish();
    }

    public void finish(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            context.finishAfterTransition();
        } else {
            context.finish();
        }
    }

    public void call(String phoneStr) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneStr));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.inflater = inflater;
        isFirstLoad = true;
        View view = initView(inflater,container,savedInstanceState);
        isPrepared = true;
        lazyLoad();
        return view;
    }

    /** 如果是与ViewPager一起使用，调用的是setUserVisibleHint */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }

    /**
     * 如果是通过FragmentTransaction的show和hide的方法来控制显示，调用的是onHiddenChanged.
     * 若是初始就show的Fragment 为了触发该事件 需要先hide再show
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }

    protected void onVisible() {
        lazyLoad();
    }

    protected void onInvisible() {
    }

    protected void lazyLoad() {
        if (!isPrepared || !isVisible || !isFirstLoad) {
            return;
        }
        isFirstLoad = false;
        initData();
    }

    protected abstract View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);

    protected abstract void initData();

    public String getTitle() {
        return TextUtils.isEmpty(fragmentTitle) ? "" : fragmentTitle;
    }

    public void setTitle(String title) {
        fragmentTitle = title;
    }

    private ProgressDialog dialog;

    public void showLoading(String message) {
        if (dialog != null && dialog.isShowing()) return;
        dialog = new ProgressDialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setMessage(message);
        dialog.show();
    }

    /**
     *
     * @param context
     * @param msg  这个不填也行，默认是加载中...
     */
    public void showDialog(Context context, @Nullable String msg) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.dialog_loading, null);// 得到加载view
        LinearLayout layout = (LinearLayout) v
                .findViewById(R.id.dialog_loading_view);// 加载布局
        TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);// 提示文字
        if(TextUtils.isEmpty(msg)){
            tipTextView.setText("加载中...");//
        }else{
            tipTextView.setText(msg);// 设置加载信息
        }


        loadingDialog = new Dialog(context, R.style.MyDialogStyle);// 创建自定义样式dialog
        loadingDialog.setCancelable(true); // 是否可以按“返回键”消失
        loadingDialog.setCanceledOnTouchOutside(true); // 点击加载框以外的区域
        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));// 设置布局
        /**
         *将显示Dialog的方法封装在这里面
         */
        Window window = loadingDialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setGravity(Gravity.CENTER);
        window.setAttributes(lp);
        window.setWindowAnimations(R.style.PopWindowAnimStyle);
        if(loadingDialog!=null&&!loadingDialog.isShowing()){
            loadingDialog.show();
        }
    }

    /**
     * 关闭dialog
     */
    public void dismissDialog() {
        if (loadingDialog != null && loadingDialog.isShowing() && isAdded()) {
            loadingDialog.dismiss();
        }
    }

    public void showToast(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    public String getAppVersionName() {
        try {
            PackageInfo Info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return Info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return "";
    }

    public int getAppVersionCode() {
        try {
            PackageInfo Info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return Info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return 0;
    }

    @OnClick({})
    public void onViewClicked(View view) {
        if(!Utils.isDoubleClick()){return;}
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dismissDialog();
    }
}

